package net.qhzw.vip.qiyu.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.result.JsonResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理
 * Created by macro on 2020/2/27.
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

//    @ResponseBody
//    @ExceptionHandler(value = Exception.class)
//    public JsonResult error(HttpServletRequest request, HttpServletResponse response,
//                            Exception e) throws IOException {
//        if (e instanceof MyException) {
//            MyException ce = (MyException) e;
//            return JsonResult.fail(ce.getCode(), ce.getMessage());
//        }
//        return JsonResult.fail(e.getMessage());
//    }


    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public JsonResult error(HttpServletRequest request, HttpServletResponse response,
                            Exception e) throws IOException {
        if (e instanceof ApiException){
            ApiException ce = (ApiException) e;
            log.info("err: " + e.getMessage());
            return JsonResult.fail(500, ce.getMessage());
        }
        if (e instanceof MyException) {
            MyException ce = (MyException) e;
            log.info("err: " + e.getMessage());
            return JsonResult.fail(ce.getCode(), ce.getMessage());
        } else if (e instanceof AccessDeniedException) {
            log.info("err: " + e.getMessage());
            return JsonResult.fail(e.getMessage());
        } else if (e instanceof HttpClientErrorException) {
            HttpClientErrorException ce = (HttpClientErrorException) e;
            String message = ce.getMessage();
            String substring = message.substring(message.indexOf("[") + 1, message.indexOf("]"));
            JSONObject jsonObject = JSON.parseObject(substring);
            String error_description = jsonObject.getString("error_description");
            log.info("err: " + e.getMessage());
            return JsonResult.fail(500, error_description);
        } else {
            log.info("err: " + e.getMessage());
            return JsonResult.fail(e.getMessage());
        }
    }


}
